package io.example;

import io.example.vertx.SpringVerticleFactory;
import io.example.vertx.SpringWorker;
import io.example.web.RestVerticle;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

/**
 * Description: VertxSpringbootDemoApplication.java .<br>
 * <p>Created Time: 2020/10/22 15:11 </p>
 *
 * @author <a href="mail to: mengxiangyuancc@gmail.com" rel="nofollow">孟祥元</a>
 */
@SpringBootApplication
@EntityScan(basePackages = "io.example.entity")
@EnableJpaRepositories(basePackages = "io.example.repository")
public class VertxSpringbootDemoApplication {
    private static final Logger logger = LoggerFactory.getLogger(VertxSpringbootDemoApplication.class);
    @Autowired
    private SpringVerticleFactory verticleFactory;

    public static void main(String[] args) {
        SpringApplication.run(VertxSpringbootDemoApplication.class, args);
    }

    @EventListener
    public void deployVerticles(ApplicationReadyEvent event) {
        Vertx vertx = Vertx.vertx();
        // 将 Spring container 中的Verticle手动注册到vertx中
        vertx.registerVerticleFactory(verticleFactory);
        // 注册 RestVerticle
        String restVerticleName = verticleFactory.prefix() + ":" + RestVerticle.class.getName();
        vertx.deployVerticle(restVerticleName, ar -> {
            if (ar.failed()) {
                logger.error("Failed to deploy book verticle", ar.cause());
            }
        });
        DeploymentOptions workerDeploymentOptions = new DeploymentOptions()
            .setWorker(true)
            .setInstances(4);
        String workerVerticleName = verticleFactory.prefix() + ":" + SpringWorker.class.getName();
        vertx.deployVerticle(workerVerticleName, workerDeploymentOptions, ar -> {
            if (ar.failed()) {
                logger.error("Failed to deploy verticle", ar.cause());
            }
        });
    }
}
